/* eslint-disable */
<template>
  <div class="user-container">
    <el-card>
      <div class="filter-container">
        <el-button type="primary" @click="handleCreate">
          新增用户
        </el-button>
        <el-button type="success" @click="handleImport">
          导入Excel
        </el-button>
        <el-button type="warning" @click="handleExport">
          导出Excel
        </el-button>
        
        <el-input
          v-model="listQuery.search"
          placeholder="搜索用户名"
          style="width: 200px; margin-left: 10px;"
          @keyup.enter="handleFilter"
        />
      </div>

      <el-table
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%; margin-top: 20px;"
        v-loading="loading"
      >
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="真实姓名" prop="realName" />
        <el-table-column label="部门" prop="department" />
        <el-table-column label="职位" prop="position" />
        <el-table-column label="电话" prop="phone" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="角色" prop="role">
          <template #default="{row}">
            <el-tag :type="row.role === '管理员' ? 'danger' : 'primary'">
              {{ row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后登录时间" prop="lastLoginTime">
          <template #default="{row}">
            {{ row.lastLoginTime ? new Date(row.lastLoginTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime">
          <template #default="{row}">
            {{ row.createTime ? new Date(row.createTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="{row}">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{row}">
            <el-button size="small" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-model:page="listQuery.page"
        v-model:limit="listQuery.limit"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入人员数据"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 xlsx/xls 文件，且不超过 10MB
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport" :loading="importing">
            确认导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination.vue'
import staffApi from '@/api/staff'

const router = useRouter()

const list = ref([])
const total = ref(0)
const loading = ref(false)
const listQuery = ref({
  page: 1,
  limit: 20,
  search: ''
})

// 导入相关
const importDialogVisible = ref(false)
const fileList = ref([])
const importing = ref(false)
const uploadRef = ref()

const getList = async () => {
  loading.value = true
  try {
    const { data } = await staffApi.getStaffs(listQuery.value)
    list.value = data.records || data
    total.value = data.total || data.length
  } catch (error) {
    console.error(error)
    ElMessage.error('获取人员列表失败')
  } finally {
    loading.value = false
  }
}

const handleFilter = () => {
  listQuery.value.page = 1
  getList()
}

const handleCreate = () => {
  router.push('/users/create')
}

const handleUpdate = (row) => {
  router.push(`/users/edit/${row.staffId}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该用户吗？', '提示', {
      type: 'warning'
    })
    await staffApi.deleteStaff(row.staffId)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }
}

const handleImport = () => {
  importDialogVisible.value = true
  fileList.value = []
}

const handleFileChange = (file) => {
  fileList.value = [file]
}

const confirmImport = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  importing.value = true
  try {
    const file = fileList.value[0].raw
    const response = await staffApi.importStaffs(file)
    
    if (response.data.success) {
      ElMessage.success(`导入成功！成功导入 ${response.data.successCount} 条数据`)
      importDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(response.data.message || '导入失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

const handleExport = async () => {
  try {
    const response = await staffApi.exportStaffs()
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `人员信息_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功！文件已保存到桌面daochu文件夹')
  } catch (error) {
    console.error(error)
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>